import { useCallback, useEffect, useState } from "react";

export interface Command {
  id: string;
  label: string;
  action: () => void;
  group?: string;
}

export interface PaletteState {
  open: boolean;
  setOpen: (value: boolean) => void;
  commands: Command[];
  register: (cmds: Command[]) => void;
  deregister: (ids: string[]) => void;
  openPalette: () => void;
}

export function useCommandPalette(): PaletteState {
  const [open, setOpen] = useState(false);
  const [commands, setCommands] = useState<Command[]>([]);

  const register = useCallback((cmds: Command[]) => {
    setCommands(prev => {
      const kept = prev.filter(cmd => !cmds.some(newCmd => newCmd.id === cmd.id));
      return [...kept, ...cmds];
    });
  }, []);

  const deregister = useCallback((ids: string[]) => {
    setCommands(prev => prev.filter(cmd => !ids.includes(cmd.id)));
  }, []);

  const handleKey = useCallback((event: KeyboardEvent) => {
    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
      event.preventDefault();
      setOpen(value => !value);
    }
  }, []);

  useEffect(() => {
    window.addEventListener("keydown", handleKey);
    return () => window.removeEventListener("keydown", handleKey);
  }, [handleKey]);

  return {
    open,
    setOpen,
    commands,
    register,
    deregister,
    openPalette: () => setOpen(true)
  };
}
